"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBDownload]
    -------------------
    * downloadTorrent(url, title) - Downloads url and names it title.torrent, then puts it in __dlpath__
"""        
import sys
import re
import TBTools
import xbmcgui
import base64
from cookielib import LWPCookieJar

class TBDownload(TBTools.TBTools):
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__
    __settings__ = sys.modules[ "__main__" ].__settings__
    __web__ = sys.modules[ "__main__" ].__web__
    __info__ = sys.modules[ "__main__" ].__info__
    __language__ = __settings__.getLocalizedString
    
    __dlpath__ = __settings__.getSetting('dlpath')
    
    def initTransmissionRPC(self):
        params = {
            'address': self.__settings__.getSetting('rpc_host'),
            'port': self.__settings__.getSetting('rpc_port'),
            'user': self.__settings__.getSetting('rpc_user'),
            'password': self.__settings__.getSetting('rpc_password')
        }
        
        import resources.lib.transmissionrpc as transmissionrpc
        
        try:
            self.transmission = transmissionrpc.Client(**params)
            return True
        except:
            (type, e, traceback) = sys.exc_info()

            message = self.__language__(9000) # Unexpected error
            if type is transmissionrpc.TransmissionError:
                if e.original:
                    if e.original.code is 401:
                        message = self.__language__(9002) # Invalid auth
                    else:
                        message = self.__language__(9001) # Unable to connect
                if xbmcgui.Dialog().yesno(self.__language__(10002), message, self.__language__(10003)):
                    self.__settings__.openSettings()
            elif type is ValueError:
                # In python 2.4, urllib2.HTTPDigestAuthHandler will barf up a lung
                # if auth fails and the server wants non-digest authentication
                message = self.__language__(9002) # Invalid auth
                if xbmcgui.Dialog().yesno(self.__language__(10002), message, self.__language__(10003)):
                    self.__settings__.openSettings()
            else:
                message = self.__language__(9000) # Unexpected error
                xbmcgui.Dialog().ok(self.__language__(10002), message)

            return False
    
    def downloadTorrent(self, url, title, sendToTransmission, magnetUrl):
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::' + 'downloadTorrent:: Initiated torrent file download for %s' % (title)
        # Cleans title to get clean filename & build download path
        torrentName = self.cleanString(title)
        __torrent__ = self.__dlpath__ + '/' + torrentName
        if magnetUrl != '':
            __torrent__ = __torrent__ + '.magnet'
        else:
            __torrent__ = __torrent__ + '.torrent'
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::' + 'downloadTorrent:: Torrent Path %s' % (__torrent__)
            
        # Download the torrent into memory
        __data__ = self.__web__.loginOpen(url)
        
        # Initiate filewrite and write the torrent from memory
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::' + 'downloadTorrent:: Writing to file %s ' % (__torrent__)
            
        if sendToTransmission:
            if self.initTransmissionRPC():
                if magnetUrl != '':
                    self.transmission.add_uri(magnetUrl)
                else:          
                    self.transmission.add(base64.b64encode(__data__))
        else:
            if magnetUrl != '':
                f = open(__torrent__, 'w');
                f.write(magnetUrl)
                f.close()
            else:
                f = open(__torrent__, 'wb')
                f.write(__data__)
                f.close()
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::' + 'downloadTorrent:: Download completed for %s' % (title)
            
    def downloadSubtitles(self, url, siteIndex, title):
        
        rawData = None
        subsNameExtension = ".srt"
        
        if self.__info__["SUBDETAILREGEXP"][siteIndex] == '(torrent-site-internal-subs)':
            #Subtitles are located inside the torrent tracker site, so maybe it will require login
            contentType = ""
            rawData = self.__web__.loginOpen(url, contentType)
            
            if re.compile('.*?Content-Type.*?rar.*?').search(contentType):
                subsNameExtension = ".rar"
        else:
            
            try:
                import resources.lib.mechanize as mechanize
            except:
                if self.__deb__:
                    print self.__plugin__ + '::DEBUG::TBDownload::' + 'downloadSubtitles:: \'mechanize\' failed to load.'
                self.showOK('ERROR','Could not load Mechanize, make sure it is installed (easy_install mechanize)')
                return
            
            # Initiate cookiejar
            self.__cj__ = LWPCookieJar()
            
            # Initiate mechanize browser
            br = mechanize.Browser()
            br.set_cookiejar(self.__cj__)
            
            # Set browser parameters needed to log in on secure+ sites.
            br.set_handle_referer(True)
            br.set_handle_robots(False)
            br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
                    
            response = br.open(url)
            rawData = response.read();
            
            if self.__deb__:
                    print self.__plugin__ + '::DEBUG::TBDownload::downloadSutbtitles primary URL loaded' 
                    print br.request.header_items()
                    print response.info()
            
            dlUrl = url
                    
            if self.__info__["SUBDETAILREGEXP"][siteIndex] != '' and re.compile('.*?Content-Type: text/html.*?').search(str(response.info())):
                #We will need to download the subtitles from their details page
                #For now we are considering that the sites are not require login
                
                urlForDlSearchResult = re.compile(self.__info__["SUBDETAILREGEXP"][siteIndex]).search(rawData)
                
                if urlForDlSearchResult:
                    dlUrl = urlForDlSearchResult.group(1)
                    dlUrl = self.replaceBadSigns(dlUrl)
                    
                    if not re.compile(".*?http.*?").search(dlUrl):
                        urlBase = re.compile(".*?http://.*?/").search(url).group(0)
                        dlUrl = urlBase + dlUrl
                       
            if self.__deb__:
                    print self.__plugin__ + '::DEBUG::TBDownload::downloadSutbtitles final URL'
                    print dlUrl
            
            br.addheaders = [("Referer", url)]
            response = br.open(dlUrl)
            rawData = response.read()
            
            if self.__deb__:
                print self.__plugin__ + '::DEBUG::TBDownload::downloadSutbtitles final URL loaded'
                print br.request.header_items()
                print response.info()            
            
            if re.compile('.*?Content-Type.*?rar.*?').search(str(response.info())):
                subsNameExtension = ".rar"
                
            br.close()
            
        if rawData != None:
            # Cleans title to get clean filename & build download path
            subsName = self.cleanString(title)
            subsName = self.__dlpath__ + '/' + subsName + "-" + str(siteIndex) + subsNameExtension            
                        
            f = open(subsName, 'wb')                        
            f.write(rawData)
            f.close()